package com.example.administrator.shzs.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.example.administrator.shzs.R;
import com.example.administrator.shzs.activity.BaiduMapLocation;
import com.example.administrator.shzs.adapter.HomeRecycleViewAdapter;
import com.example.administrator.shzs.adapter.HomeShopListAdapter;
import com.example.administrator.shzs.app.MyApplication;
import com.example.administrator.shzs.entity.IndexCarousel;
import com.example.administrator.shzs.entity.MerchantData.ListBean;
import com.example.administrator.shzs.parse.ParseIndexCarousel;
import com.example.administrator.shzs.parse.ParseIndexXrecycleView;
import com.example.administrator.shzs.ui.CategoryActivity;
import com.example.administrator.shzs.ui.OfflinePayActivity;
import com.example.administrator.shzs.ui.SearchActivity;
import com.example.administrator.shzs.ui.ShopActivity;
import com.example.administrator.shzs.url.Contents;
import com.example.administrator.shzs.utils.NetworkImageHolderView;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;


/**
 * 首页 Fragment
 */

public class HomeFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener {

    @Bind(R.id.index_progressBar)
    ProgressBar indexProgressBar;

    @Bind(R.id.rl_title)
    RelativeLayout rlTitle;

    private LinearLayout Index_search;
    private LinearLayout No_Data_Show;

    //轮播图
    private ConvenientBanner convenientBanner;
    //实体类
    private List<IndexCarousel> datalist = new ArrayList<>();

    //定位点击父控件
    private LinearLayout mllLocation;

    //定位显示控件
    private TextView tvLocation;
    //特色分类
    private RecyclerView mRecycleview;
    private HomeRecycleViewAdapter mRecycleAdapter;
    private List<Map<Object, Object>> datalistZ = new ArrayList<>();


    //商家展示
    private XRecyclerView xRecyclerView;
    private HomeShopListAdapter mShopListAdapter;
    private List<ListBean> datalistX; //默认加载
    private List<ListBean> datalistXo;//更多加载

    //加载页数
    private int page = 1;

    /**
     * 轮播图控件高度
     */
    private int height = 0;

    /**
     * item滑动的高度
     */
    int y = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getActivity()));
        View view = inflater.inflate(R.layout.fragment_index, null);
        //初始化XRecyclerView数据
        setXRecyclerView(inflater, view);
        ButterKnife.bind(this, view);

        //加载中间特色的数据
        iniData();

        //从网络获取轮播图数据
        iniDataFromWebItem();

        //商家列表 数据
        iniDataFromWebXItem(1);

        //设置下拉刷新  上拉加载
        setRecyclerView();

        return view;
    }

    /**
     * XRecyclerView的Item点击事件
     */
    private void setListeners() {


        mShopListAdapter.setOnItemClickListener(new HomeShopListAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(ListBean merchantData) {

                Intent intent = new Intent(getActivity(), ShopActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("MerchantData", merchantData);
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void onShopPayClick(ListBean merchantData) {
                //到店付
                Intent offlinePay = new Intent(getActivity(), OfflinePayActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("merchantdata", merchantData);
                offlinePay.putExtras(bundle);
                offlinePay.putExtra("HomeFragment", true);
                startActivity(offlinePay);
            }
        });
    }


    /**
     * XRecyclerView的滑动监听
     *
     * @param convenientBanner 轮播图
     */
    private void glideListeners(final ConvenientBanner convenientBanner) {

        ViewTreeObserver observer = convenientBanner.getViewTreeObserver();

        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                rlTitle.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                //获取轮播图的高度
                height = convenientBanner.getHeight();


                xRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrolled(RecyclerView recyclerView, int x, int dy) {
                        super.onScrolled(recyclerView, x, dy);

                        y += dy;
                        if (y <= 0) {   //设置标题的背景颜色

                            rlTitle.setBackgroundColor(Color.argb((int) 0, 144, 151, 166));
                        } else if (y > 0 && y <= height) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变

                            float scale = (float) y / height;
                            float alpha = (255 * scale);

                            rlTitle.setBackgroundColor(Color.argb((int) alpha, 144, 112, 0));

                        } else {    //滑动到banner下面设置普通颜色

                            rlTitle.setBackgroundResource(R.color.colorOrange);

                        }
                    }
                });
            }
        });

    }


    /**
     * 设置下拉刷新  上拉加载
     */
    private void setRecyclerView() {
        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

                iniDataFromWebXItem(1);
            }

            @Override
            public void onLoadMore() {

                page++;
                iniDataFromWebXItem(page);

            }
        });

    }


    /**
     * 设置数据
     */
    private void iniData() {

        final int[] image = new int[]{R.mipmap.home_icon1_03, R.mipmap.home_icon1_24, R.mipmap.home_icon1_76, R.mipmap.home_icon1_11, R.mipmap.home_icon1_26,
                R.mipmap.home_icon1_05, R.mipmap.home_icon1_07, R.mipmap.home_icon1_09, R.mipmap.home_icon1_18, R.mipmap.home_icon1_20};
        final String[] name = new String[]{"美食", "酒店", "酒吧/KTV", "商超", "生鲜/调料", "外卖",
                "早餐", "夜宵", "蛋糕", "水果"};
        final String[] sortid = new String[]{"18", "26", "48", "27", "30", "12", "60", "61", "31", "29"};

        for (int i = 0; i < image.length; i++) {
            Map<Object, Object> map = new HashMap<>();
            map.put("image", image[i]);
            map.put("name", name[i]);
            map.put("sortid", sortid[i]);
            datalistZ.add(map);
        }
        mRecycleAdapter = new HomeRecycleViewAdapter(datalistZ, getActivity());
        mRecycleview.setAdapter(mRecycleAdapter);
//        //RecyclerView的item点击事件
        mRecycleAdapter.setIconRecycleOnclickListent(new HomeRecycleViewAdapter.IconRecycleOnclickListent() {
            @Override
            public void onItemClick(View view, int postion) {
                Intent intent = new Intent(getActivity(), CategoryActivity.class);
                intent.putExtra("name", name[postion]);
                intent.putExtra("sortid", sortid[postion]);
                startActivity(intent);
            }
        });

    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:

                    No_Data_Show.setVisibility(View.VISIBLE);
                    xRecyclerView.refreshComplete();
                    xRecyclerView.loadMoreComplete();
                    break;
                case 1:
                    //轮播图
                    if (datalist.size() == 1) {
                        convenientBanner.stopTurning();
                    } else {
                        convenientBanner.startTurning(5000);
                    }

                    convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
                        @Override
                        public NetworkImageHolderView createHolder() {
                            return new NetworkImageHolderView();
                        }
                    }, datalist)
                            //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                            .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                            //轮播图的点击事件
                            .setOnItemClickListener(new OnItemClickListener() {
                                @Override
                                public void onItemClick(int position) {
                                    //


                                }
                            });
                    break;
                case 2:

                    No_Data_Show.setVisibility(View.GONE);

                    mShopListAdapter = new HomeShopListAdapter(getActivity(), datalistX);
                    xRecyclerView.setAdapter(mShopListAdapter);
                    //点击事件
                    setListeners();
                    xRecyclerView.refreshComplete();
                    break;

                case 3:

                    No_Data_Show.setVisibility(View.GONE);

//                   将获取的数据集合添加到原有的集合
                    datalistX.addAll(datalistXo);
                    mShopListAdapter.notifyDataSetChanged();
                    datalistXo.clear();
                    xRecyclerView.loadMoreComplete();
                    break;

            }
        }
    };


    private String lat = MyApplication.app.getLatitude() + "";
    private String lng = MyApplication.app.getLongitude() + "";

    /**
     * 首页商家列表 数据
     */

    private void iniDataFromWebXItem(final int page) {

        //pagesize=16&languageType=2&shoptype=0&types=1&pageindex=1&sortname=SortNum&sortflag=1&lat=35.199013&lng=114.675170
        String url = Contents.INDEX_XRECYCLE + "?pagesize=16&languageType=2&shoptype=0&types=1&pageindex="
                + page + "&sortname=SortNum&sortflag=1&lat=35.199013&lng=114.675170";

        Request request = new Request.Builder().url(url).build();


        Log.e("Life", "商家列表" + request.toString());


        Contents.okhttp.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String request = response.body().string();

                if (page == 1) {
                    try {
                        datalistX = ParseIndexXrecycleView.getIndexXrecyclView(request);
                        if (datalistX.size() > 0) {
                            handler.sendEmptyMessage(2);
                        } else {
                            handler.sendEmptyMessage(0);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        datalistXo = ParseIndexXrecycleView.getIndexXrecyclView(request);
                        if (datalistXo.size() > 0) {
                            handler.sendEmptyMessage(3);
                        } else {
                            handler.sendEmptyMessage(0);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    /**
     * 获取轮播图数据
     */
    private void iniDataFromWebItem() {
        Request request = new Request.Builder().url(Contents.INDEX_Carouse).build();
        Contents.okhttp.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String request = response.body().string();
                datalist = ParseIndexCarousel.getIndexCarousel(request);
                if (datalist.size() > 0) {
                    handler.sendEmptyMessage(1);
                } else {
                    handler.sendEmptyMessage(0);
                }
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        convenientBanner.startTurning(3000);

    }

    @Override
    public void onPause() {
        super.onPause();
        convenientBanner.stopTurning();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.Index_Location:
                //进入地图界面
                Intent intent = new Intent(getActivity(), BaiduMapLocation.class);
                startActivity(intent);
                break;
        }
    }


    /**
     * 设置Xrecycler数据
     */
    private void setXRecyclerView(LayoutInflater inflater, View view) {

        xRecyclerView = (XRecyclerView) view.findViewById(R.id.Index_XrecycleView);


        //初始化定位控件
        mllLocation = (LinearLayout) view.findViewById(R.id.Index_Location);
        mllLocation.setOnClickListener(this);
        //没有数据信息展示
        No_Data_Show = (LinearLayout) view.findViewById(R.id.No_Data_show);

        //获取当前位置信息
        tvLocation = (TextView) view.findViewById(R.id.tv_Location);
        String loaction = MyApplication.app.getAddress();
        tvLocation.setText(loaction == null ? "位置获取失败" : loaction);
        Index_search = (LinearLayout) view.findViewById(R.id.Index_search);

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        xRecyclerView.setLayoutManager(manager);
        xRecyclerView.setRefreshing(true);


        xRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.SquareSpin);
        //刷新箭头
        xRecyclerView.setArrowImageView(R.mipmap.ic_pulltorefresh_arrow);

        //引入xrecyclview头部
        View head = inflater.inflate(R.layout.home_xrecycleview_head, null);
        convenientBanner = (ConvenientBanner) head.findViewById(R.id.convenientBanner);


        mRecycleview = (RecyclerView) head.findViewById(R.id.Index_RecyclerView);
        GridLayoutManager manager2 = new GridLayoutManager(getActivity(), 5);
        mRecycleview.setLayoutManager(manager2);

        Index_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            }
        });


        xRecyclerView.addHeaderView(head);
        glideListeners(convenientBanner);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

}
